package com.oasistudio.tk.connector.imp;

import java.io.UnsupportedEncodingException;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

import org.json.JSONArray;
import org.json.JSONObject;

import android.util.Log;

import com.oasistudio.tk.connector.TopAPIConnectorHelper;
import com.oasistudio.tk.connector.TopAPIHelper;
import com.oasistudio.tk.connector.TopApiRequest;
import com.oasistudio.tk.connector.TopApiResponse;
import com.taobao.tbw.common.TBWContext;

public class TaobaokeShopsGetConnector implements TopAPIConnectorHelper {
	private String keyword;//店铺类目关键字
	private String startCredit;
	private String endCredit;
	private String outerCode;//淘宝客unionid
	private int pageNO;//页码
	private int pageSize;//每页记录数

	private String fields="user_id,shop_title,click_url,commission_rate,seller_credit,shop_type,total_auction,auction_count";
	
	public TaobaokeShopsGetConnector(){
	}
	
	public void setStartCredit(String startCredit){
		this.startCredit = startCredit;
	}
	
	public void setEndCredit(String endCredit){
		this.endCredit = endCredit;
	}
	
	public void setKeyword(String keyword){
		this.keyword = keyword;
	}
	public void setPageNO(int pageNO){
		this.pageNO = pageNO;
	}
	public void setPageSize(int pageSize){
		this.pageSize = pageSize;
	}
	public void setOuterCode(String outerCode){
		this.outerCode = outerCode;
	}

	public void setFields(String fields){
		this.fields = fields;
	}

	@Override
	public Object asyncPaser(byte[] part) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String getApiUrl() {
		TopApiRequest request = new TopApiRequest();
		TreeMap<String, String> params = new TreeMap<String, String>();
		params.put("app_key", TBWContext.getInstance().getAppKey());
		//params.put("app_secret", TBWContext.getInstance().getAppSecret());
		params.put("partner_id", "top-apitools");
		params.put("sign_method", "md5");
		params.put("format", "json");
		params.put("v", "2.0");

		params.put("method", "taobao.taobaoke.shops.get");
		params.put("timestamp", TopAPIHelper.getTopTimestamp());
		//params.put("session", TBWContext.getInstance().getTopsession());
		
		params.put("keyword", keyword);
		params.put("pid", TBWContext.getInstance().getPID());
		params.put("page_no", this.pageNO+"");
		params.put("page_size", this.pageSize+"");
		params.put("outer_code", this.outerCode);
		params.put("sort", "commissionNum_desc");
		if(startCredit!=null){
			params.put("start_credit", startCredit);
		}
		if(endCredit != null){
			params.put("end_credit", endCredit);
		}
		
//		System.out.println("TaobaokeItemsGetConnector.getApiUrl() keyword = "+this.keyword);
//		System.out.println("TaobaokeItemsGetConnector.getApiUrl() pid = "+TBWContext.getInstance().getPID());
//		System.out.println("TaobaokeItemsGetConnector.getApiUrl() page_no = "+this.pageNO+"");
//		System.out.println("TaobaokeItemsGetConnector.getApiUrl() page_size = "+this.pageSize+"");
//		System.out.println("TaobaokeItemsGetConnector.getApiUrl() outer_code = "+this.outerCode);
		
		params.put("fields", fields);
		//params.put("is_mobile", "true");//	
		request.params = params;
		String url = request.generalRequestUrl(true);
		//System.out.println("TaobaokeItemsGetConnector.getApiUrl() url = "+url);
		//url = "http://gw.api.taobao.com/router/rest?sign=DB8F57663686F5E85EE4E4C1B0FEB060&timestamp=2012-03-11+00%3A00%3A38&v=2.0&app_key=12129701&method=taobao.taobaoke.items.get&partner_id=top-apitools&format=json&page_size=10&outer_code=SearchedList&keyword=%E8%BF%9E%E8%A1%A3%E8%A3%99&pid=14654733&page_no=1&fields=num_iid,title,nick,pic_url,price,click_url,commission,commission_rate,commission_num,commission_volume,shop_click_url,seller_credit_score,item_location,volume";
		return url;
	}
	
	@Override
	public Object syncPaser(byte[] all) {
		NumberFormat nf = NumberFormat.getInstance();
		nf.setMinimumFractionDigits(2);
		nf.setMaximumFractionDigits(2);
		ShopsInfo shopsInfo = new ShopsInfo();
		try {
			TopApiResponse response = new TopApiResponse("taobaoke_shops_get_response");
			String str = new String(all, "UTF-8");
			Log.d("return msg:", str);
			if (response.parseResult(str).success) {
				shopsInfo.isSuccess = true;
				JSONObject jsObj = response.data;
				if(jsObj.has("taobaoke_shops")){
					shopsInfo.totalResults = jsObj.optInt("total_results");
					List<Shop> shops = new ArrayList<Shop>();
					shopsInfo.shops = shops;
					JSONArray array = jsObj.optJSONObject("taobaoke_shops").optJSONArray("taobaoke_shop");
					System.out.println("TaobaokeShopsGetConnector.syncPaser() array ="+array);
					for(int i=0; i<array.length(); i++){
						JSONObject shopJSON= array.getJSONObject(i);
						Shop shop = new Shop();
						shop.shop_title = shopJSON.optString("shop_title");
						shop.user_id = shopJSON.optLong("user_id");
						shop.click_url = shopJSON.optString("click_url");
						//shop.commission_rate = shopJSON.optString("commission_rate");
						String commissionRateString = shopJSON.optString("commission_rate");
						//System.out.println("TaobaokeItemsConvertConnector.syncPaser() commissionRateString = "+commissionRateString);
						try{
							double commissionRateDouble = Double.valueOf(commissionRateString);
							shop.commission_rate = nf.format(commissionRateDouble*TBWContext.FINAL_RATE);
							//System.out.println("TaobaokeItemsConvertConnector.syncPaser() shop.commission_rate = "+shop.commission_rate);
						}catch(Exception e){
							//e.printStackTrace();
						}

						shop.click_url = shopJSON.optString("click_url");
						shop.commission_rate = shopJSON.optString("commission_rate");
						shop.seller_credit = shopJSON.optString("seller_credit");
						shop.shop_type = shopJSON.optString("shop_type");	
						shop.total_auction = shopJSON.optString("total_auction");
						shop.auction_count = shopJSON.optInt("auction_count");
						shops.add(shop);
					}
				}
			} else {
				shopsInfo.isSuccess = false;
				shopsInfo.errCode = response.errCode;
				shopsInfo.errInfo = response.errInfo;
			}

		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return shopsInfo;
	}

	public static class ShopsInfo {
		public String errCode;
		public String errInfo;
		public Boolean isSuccess;
		public Number totalResults;
		public List<Shop> shops = new ArrayList<Shop>();
	}
	public static class Shop{
		public Number user_id;
		public String shop_title;
		public String click_url;
		public String commission_rate;
		public String seller_credit;
		public String shop_type;
		public String total_auction;
		public Number auction_count;
		
		public String toString(){
			StringBuilder sb = new StringBuilder();
			sb.append("user_id:"+user_id);
			sb.append(";commission_rate:"+commission_rate);
			sb.append(";shop_title:"+shop_title);
			sb.append(";shop_type:"+shop_type);
			sb.append(";seller_credit:"+seller_credit);
			return sb.toString();
		}
	}
}



